import java.io.FileOutputStream;
import java.util.HashMap;


public class FileUtility {
	public static String BytesToBase64(byte[] buffer, int length){
		//String base64 = "";
		StringBuffer strBuff = new StringBuffer("");
		
		for(int i = 0; i< length; i++){
			strBuff.append(getByteHexString(Integer.toHexString(buffer[i])));
		}
		return strBuff.toString();
	}
	

	
	public static byte[] Base64ToBytes(String base64){
		
		int length = base64.length();
		int n = length / 2;
		byte[] buffer = new byte[n];
		int j = 0;
		for(int i=0; i < length; i+=2){
			buffer[j++] = getByteValue(base64.substring(i, i+2));
		}
		return buffer;
	}
	
	private static String getByteHexString(String hex){
		int l = hex.length();
		if(l == 1)
			return "0" + hex.toUpperCase();
		if(hex.equalsIgnoreCase(""))
			return "00";
		return hex.substring(l-2, l).toUpperCase();
	}
	
	private static byte getByteValue(String hex){
		int i = 0;
		try{
			i = Integer.valueOf(hex, 16);
		}catch(Exception e){}
		return (byte)i;
	}
	
	public static void saveFileUpdate(HashMap<Integer, FilePart> partList, FileOutputStream f){
		for (int i : partList.keySet()) {
			try {
				FilePart p = partList.get(new Integer(i));
				if(p.getStatus() == 1) continue;
				//write file
				f.write(p.getData());
				p.setStatus(1);
				break;
			} catch (Exception e) { return; }
		}
	}
	
	public static boolean checkFileDone(HashMap<Integer, FilePart> partList){
		for (int i : partList.keySet()) {
			try {
				FilePart p = partList.get(new Integer(i));
				if(p.getStatus() == 1) continue;
				return false;
			} catch (Exception e) { return false; }
		}
		return true;
	}
	
}
